package com.zkhz.base.security.util;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Description Bearer 类型的token工具
 *
 * @author wuzeqin
 * @date 2020/6/21
 **/
public class BearerTokenUtil {

    private BearerTokenUtil(){}

    /**
     * 提取token
     */
    public static String extractToken(HttpServletRequest request) {
        // first check the header...
        Enumeration<String> headers = request.getHeaders("Authorization");
        while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that)
            String value = headers.nextElement();
            if ((value.toLowerCase().startsWith("bearer"))) {
                String authHeaderValue = value.substring("bearer".length()).trim();
                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                return authHeaderValue;
            }
        }

        return request.getParameter("access_token");
    }
}
